<?php

namespace app\common\service;


use app\common\exception\ApiException;
use think\Cache;

class BaseToken {
    public static function generateToken() {
        //32个字符组成一组随机字符串
        $randChars = getRandChar(32);
        //用三组字符串，进行md5加密
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //salt 盐
        $salt = config('secure.token_salt');
        return md5($randChars . $timestamp . $salt);
    }

    public static function getCurrentTokenVar($key, $value) {
        if (!is_array($value)) {
            $value = json_decode($value, true);
        }
        if (array_key_exists($key, $value)) {
            return $value[$key];
        } else {
            return false;
        }
    }

    public static function saveToCache($value) {
        $key             = self::generateToken();
        $token_expert_in = config('setting.token_expire_in');
        $result          = cache($key, json_encode($value), $token_expert_in);
        if (!$result) {
            throw new ApiException('服务器错误', 500);
        }
        return $key;
    }

    public static function updateCache($key, $value) {
        Cache::set($key, $value, config('setting.token_expire_in'));
    }
}